//
//  KDWSBaseBoard.m
//  PublicSentimentMonitorSystem
//
//  Created by 魏强 on 15/11/28.
//  Copyright © 2015年 魏强. All rights reserved.
//

#import "KDWSBaseBoard.h"
#import "RightPageBtn.h"
#import "KDDatePickerView.h"
#import "KDDateModel.h"
#import "KDRightPageBtnModel.h"
#import "UIView+Extension.h"
#import "KDMBaseBoardModel.h"
#import "SVProgressHUD.h"
#define BEGIN_TIME @"beginTime"
#define END_TIME @"endTime"
@interface KDWSBaseBoard ()<UITextFieldDelegate,KDDatePickerViewDelegate>
@property (weak, nonatomic) IBOutlet RightPageBtn *customBtn;//“自定义”按钮
@property (nonatomic, retain) NSDateFormatter *fmt;
/***  装“信息类型”板块的view */
@property (weak, nonatomic) IBOutlet UIView *firstView;
/***  装“信息隐藏属性”板块的View */
@property (weak, nonatomic) IBOutlet UIView *secondBoard;
/***  装“信息属性”板块的view */
@property (weak, nonatomic) IBOutlet UIView *thirdView;
@property (weak, nonatomic) IBOutlet UIView *datePickerView;//装时间选择的总View
/***  装“信息时间”板块的view */
@property (weak, nonatomic) IBOutlet UIView *fourthView;
/***  装“业务”板块的view */
@property (weak, nonatomic) IBOutlet UIView *addressView;

@property (weak, nonatomic) IBOutlet UIButton *beginBtn;

@property (weak, nonatomic) IBOutlet UIButton *endBtn;
@property (nonatomic, strong) KDDateModel *dateModel;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *secondBoard_Height;


/***  datePickerView的高度约束 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *datePickerViewConstraint_Height;
/*** 确定按钮 */
@property (weak, nonatomic) IBOutlet RightPageBtn *confirmBtn;
/***  view底层的scrollView */
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
/***  scrollView的高度约束，其实是containsize */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scrollView_constraint_width;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scrollView_constraint_height;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *firstView_constraint_height;
/**
 *  信息属性板块的高度约束
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *thirdView_constraint_Height;

/**
 *  地址板块的高度约束
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *addressView_Constraint_Height;


/*** 信息范畴页面被选中的按钮 */
@property (nonatomic, weak) RightPageBtn *scopeSelectBtn;
/*** 信息属性页面被选中的按钮 */
@property (nonatomic, weak) RightPageBtn *effectSelectBtn;
/*** 信息时间页面被选中的按钮 */
@property (nonatomic, weak) RightPageBtn *timeSelectBtn;
/**
 *  中性按钮
 */
@property (weak, nonatomic) IBOutlet RightPageBtn *neutralBtn;
/**
 *  正面按钮
 */
@property (weak, nonatomic) IBOutlet RightPageBtn *positiveBtn;
/**
 *  当前是不是已经打开了侧边栏
 */
@property (nonatomic, assign, getter=isOpen) BOOL open;
/**
 *  当下打开的DatePickerView
 */
@property (nonatomic, weak) KDDatePickerView *pickView;

@end
@implementation KDWSBaseBoard
#pragma mark -懒加载区


- (KDDateModel *)dateModel
{
    if (!_dateModel) {
        _dateModel = [[KDDateModel alloc]init];
    }
    return _dateModel;
}
- (NSDateFormatter *)fmt
{
    if (!_fmt) {
        _fmt = [[NSDateFormatter alloc]init];
        _fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];;
        _fmt.dateFormat = @"yyyy-MM-dd";
    }
    return _fmt;
}
# pragma mark - 初始化布局区

//初始化方法
+ (instancetype)baseboard
{
    KDWSBaseBoard *board = [[[NSBundle mainBundle] loadNibNamed:@"KDWSBaseBoard" owner:nil options:nil]lastObject];
//    board.tintColor = KDColor;
//    [board.confirmBtn setTitleColor:KDHeadColor forState:UIControlStateNormal];
    board.confirmBtn.clipsToBounds = YES;
    //添加手势
    UITapGestureRecognizer *hide = [[UITapGestureRecognizer alloc] init];
    [hide addTarget:board action:@selector(hideTheKeyBoard)];
    [board addGestureRecognizer:hide];
    
    //设置开始按钮和结束按钮的边框风格
    //
    board.beginBtn.layer.borderWidth = 0.6f;
    board.beginBtn.layer.borderColor = WQColor(210 , 210, 210).CGColor;
    board.endBtn.layer.borderWidth = 0.6f;
    board.endBtn.layer.borderColor = WQColor(210 , 210, 210).CGColor;
    
    return board;
}
- (void)layoutSubviews
{
    [super layoutSubviews];
    
}
/**
 *  开关的set方法
 */
- (void)setOpen:(BOOL)open{
    _open = open;
    if (open) {//说明正在打开
        [self setUpAll];
    }else{
        if (self.pickView) {
            [self.pickView hideDatePickerView];
        }
    }
}
- (void)drawRect:(CGRect)rect{
    [super drawRect:rect];
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)setUpAll{
    //    NSDictionary *dic = @{@"idstr":self.model.idstr};
    self.model = nil;
    if (!self.model.webSrcType) {
        //        KDMBaseBoardModel *model = [[KDMBaseBoardModel alloc]init];
        self.model.webSrcType = @"0";
        //获取一周前的日期
        NSDate *newdate = [[NSDate date] initWithTimeInterval:- (24 *60 * 60 * 6 )sinceDate:[NSDate date]];
        self.model.startTime = [self.fmt stringFromDate:newdate];
        self.model.endTime = @"";
        self.model.timeIndex = @"9";
        self.model.docType = @"0";
        self.model.bussiness = @"0";
        //        self.model = model;
        
        //        self.model.showReginType = self.showReginType;
        //        [KDMBaseBoardTool saveBaseBoardModel:self.model];
    }
    NSDate *begin = [self.fmt dateFromString:self.model.startTime ];
    NSDate *end = [self.fmt dateFromString:self.model.endTime];
    if (begin) {
        self.dateModel.beginDate = begin;
    }else{
        self.dateModel.beginDate = [NSDate date];
    }
    if (end) {
        self.dateModel.endDate = end;
    }else{
        self.dateModel.endDate = [NSDate date];
    }
    [self refreshTitle];
//    self.scrollView.contentSize = CGSizeMake(1, screenH +50 );
    [self getAllData];
    self.model.webSrcType = [NSString stringWithFormat:@"%ld", self.outSideKindType];
    self.scopeSelectBtn = (RightPageBtn *)[self.firstView viewWithTag:self.model.webSrcType.integerValue +1];
    self.effectSelectBtn = (RightPageBtn *)[self.thirdView viewWithTag:self.model.docType.integerValue + 6];
    self.timeSelectBtn = (RightPageBtn *)[self.fourthView viewWithTag:self.model.timeIndex.integerValue ];
    self.scopeSelectBtn.selected = YES;self.effectSelectBtn.selected = YES;
    self.timeSelectBtn.selected = YES;
    [self scopeViewBtnClick:self.scopeSelectBtn];
    [self effectBtnClick:self.effectSelectBtn];
    [self timeViewBtnClick:self.timeSelectBtn];
    self.beginBtn.enabled = YES;
    self.endBtn.enabled = YES;
}
//取得所有btn的模型的数据
- (void) getAllData
{
    for (RightPageBtn *btn in self.firstView.subviews) {//信息类型
        if ([btn isKindOfClass:[RightPageBtn class]]) {
            KDRightPageBtnModel *model = [[KDRightPageBtnModel alloc]init];
            //请求需要的参数
            model.type = @"webSrcType";
            model.sign = [NSString stringWithFormat:@"%ld",(long)btn.tag -1];
            btn.model = model;
        }
    }
    //信息属性正反面
    for (RightPageBtn *btn in self.thirdView.subviews) {
        if (btn.tag >= 6 && btn.tag <= 9 &&[btn isKindOfClass:[RightPageBtn class]] ) {
            if (!btn.model) {
                KDRightPageBtnModel *model = [[KDRightPageBtnModel alloc]init];
                model.type = @"docType";
                model.sign = [NSString stringWithFormat:@"%ld",(long)btn.tag -6];
                btn.model = model;
            }
        }
    }
    //信息业务
    for (RightPageBtn *btn in self.addressView.subviews) {
        if (btn.tag >= 1 && btn.tag <= 2 &&[btn isKindOfClass:[RightPageBtn class]] ) {
            if (!btn.model) {
                KDRightPageBtnModel *model = [[KDRightPageBtnModel alloc]init];
                model.type = @"address";
                model.sign = [NSString stringWithFormat:@"%ld",(long)btn.tag -1];
                btn.model = model;
            }
        }
    }
    //信息时间
    for (RightPageBtn *btn in self.fourthView.subviews) {
        if (btn.tag >= 9 &&[btn isKindOfClass:[RightPageBtn class]]) {
            if (!btn.model) {
                KDRightPageBtnModel *model = [[KDRightPageBtnModel alloc]init];
                model.type = @"startTime";
                model.sign = [NSString stringWithFormat:@"%ld",(long)btn.tag];
                btn.model = model;
            }
        }
    }
}
#pragma mark - 事件点击区
/**
 *  信息范畴板块的按钮被点击
 *
 *  @param sender 被点击的按钮
 */
- (IBAction)scopeViewBtnClick:(RightPageBtn *)sender {
    //    KDLog(@"%ld",(long)sender.tag);
    //在信息范畴中遍历选择
    for (RightPageBtn *btn in self.firstView.subviews)
    {
        if ([btn isKindOfClass:[RightPageBtn class]]) {
            if (btn.selected) {//找出之前选中的那个
                btn.selected = NO;
                //                break;
            }
        }
    }
    sender.selected = YES;
    //特殊情况：当国内按钮或媒体按钮被点击了，进入这个方法
    self.model.webSrcType = sender.model.sign;
    if (self.delegate && [self.delegate respondsToSelector:@selector(kindTypeBtnClickWithBtnTag:)]) {
        [self.delegate kindTypeBtnClickWithBtnTag:self.model.webSrcType.integerValue];
    }
}
/**
 *  信息属性板块的按钮被点击了
 *
 *  @param sender 被点击的按钮
 */
- (IBAction)effectBtnClick:(RightPageBtn *)sender {
    for (RightPageBtn *btn in self.thirdView.subviews){
        if ([btn isKindOfClass:[UIButton class]]) {
            if (btn.selected) {
                btn.selected = NO;
                //                break;
            }
        }
    }
    sender.selected = YES;
    self.model.docType = sender.model.sign;
}

/**
 *  信息时间板块的按钮被点击了
 *
 *  @param sender 被点击的按钮
 */
- (IBAction)timeViewBtnClick:(id)sender{
    
    RightPageBtn *rightBtn = (RightPageBtn *)sender;
    {for (RightPageBtn *btn in self.fourthView.subviews)
    {
        if ([btn isKindOfClass:[RightPageBtn class]]) {
            if (btn.selected) {
                btn.selected = NO;
                //                    break;
            }
        }
    }
    }
    rightBtn.selected = YES;
    self.model.startTime = rightBtn.model.startTime;
    self.model.endTime = rightBtn.model.endTime;
    self.model.beginDate = rightBtn.model.beginDate;
    self.model.endDate = rightBtn.model.endDate;

    self.model.timeIndex = rightBtn.model.sign;
    if (self.customBtn.selected) {//如果自定义按钮被选中，那么就打开日期选择器
        [self openDatePicker];
    }
    else{//如果没有被选中，就关闭日期选择器
        [self removeDatePicker];
    }
}
//显示日期选择
- (void)openDatePicker
{
    
    self.datePickerView.hidden = NO;
    [UIView animateWithDuration:0.3f animations:^{
        self.datePickerView.alpha = 1.0f;
        self.datePickerViewConstraint_Height.constant = 40;
        [self layoutIfNeeded];
    }];
    NSDate *curDate = [NSDate date];
    self.curDate = curDate;
    //开始时间
    NSString *begin = [self.fmt stringFromDate:self.dateModel.beginDate];
    //结束时间
    NSString *end = [self.fmt stringFromDate:self.dateModel.endDate];
    self.model.startTime = begin;
    self.model.endTime = end;
    self.scrollView.contentSize = (iOS7)? CGSizeMake(1, screenH  + 130): CGSizeMake(1, screenH  +40 - 49);
//        KDLog(@"%@",NSStringFromCGSize(self.scrollView.contentSize));
    [self refreshTitle];
}
//隐藏日期选择
- (void)removeDatePicker
{
    
    [UIView animateWithDuration:0.3f animations:^{
        self.datePickerViewConstraint_Height.constant = 0;
        [self layoutIfNeeded];
        self.datePickerView.alpha = 0;

    }completion:^(BOOL finished) {
        self.datePickerView.hidden = YES;
        self.scrollView.contentSize = (iOS7)? CGSizeMake(1, screenH  + 90): CGSizeMake(1, screenH  -49);
    }];
    
//    KDLog(@"%@",NSStringFromCGSize(self.scrollView.contentSize));
}
/**
 *  开始时间按钮被点击了
 *
 */
- (IBAction)beginBtnClick:(id)sender {
    [self showPickViewWithType:KDDatePickerTypeBegin];
    
}

//结束时间按钮被点击了
- (IBAction)endBtnClick:(id)sender {
        [self showPickViewWithType:KDDatePickerTypeEnd];
}
/**
 *  type：0:begin；1:end
 */
- (void)showPickViewWithType:(NSInteger)type{
    KDDatePickerView *pickView;
    if (type) {
        pickView = [KDDatePickerView showWithType:type andDate:self.dateModel.endDate];
    }else{
        pickView = [KDDatePickerView showWithType:type andDate:self.dateModel.beginDate];
    }
    
    pickView.delegate = self;
    
}
/**
 *  确定按钮被点击了
 */
- (IBAction)confirmBtnClick:(RightPageBtn *)sender {
    KDMBaseBoardModel *model = self.model;
    if (self.delegate &&[ self.delegate respondsToSelector:@selector( baseBoard:confirmBtnDidClickWithBaseBoardModel:)]) {
        [self.delegate baseBoard:self confirmBtnDidClickWithBaseBoardModel:model];
    }
}
#pragma mark - 刷新字体
- (void)refreshTitle
{
    //开始时间
    NSString *begin = [self.fmt stringFromDate:self.dateModel.beginDate];
    //结束时间
    NSString *end = [self.fmt stringFromDate:self.dateModel.endDate];
    [self.beginBtn setTitle:begin forState:UIControlStateNormal];
    [self.endBtn setTitle:end forState:UIControlStateNormal];
}
#pragma mark - KDDatePickerViewDelegate
/**
 *  datepicker的设置按钮被点击了
 *
 *  @param pickerView 时间选择器
 *  @param date       被选中的时间
 *  @param type      确定是开始时间还是结束时间
 */
- (void)datePickerView:(KDDatePickerView *)pickerView settingBtnClickWithDate:(NSDate *)date andType:(KDDatePickerType)type
{
    //    self.beginBtn.enabled = YES;
    //    self.endBtn.enabled = YES;
    NSComparisonResult result1 = [[NSDate date] compare:date];
    if (result1 == -1) {
        [SVProgressHUD setOffsetFromCenter:UIOffsetMake(self.centerX - screenW *0.5, 0)];
        [SVProgressHUD showInfoWithStatus:@"选取时间应小于或等于今天！" maskType:SVProgressHUDMaskTypeGradient];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if (type != KDDatePickerTypeBegin) {
                [self endBtnClick:self.endBtn];
            }else{
                [self beginBtnClick:self.beginBtn];
            }
        });
        return;
    }
    if (type == KDDatePickerTypeBegin) {//如果是开始时间被设置了
        //比较开始时间和结束时间，看看哪个大
        NSComparisonResult result = [date compare:self.dateModel.endDate];
        if (result != - 1) {//开始时间大于结束时间
            [SVProgressHUD setOffsetFromCenter:UIOffsetMake(self.centerX - screenW *0.5, 0)];
            [SVProgressHUD showInfoWithStatus:@"开始时间应小于结束时间！" maskType:SVProgressHUDMaskTypeGradient];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self endBtnClick:self.endBtn];
            });
            return;
        }else{//开始时间小于结束时间
            self.dateModel.beginDate = date;
        }
    }
    else{
        NSComparisonResult result = [date compare:self.dateModel.beginDate];
        if (result == -1) {//开始时间大于结束时间
            [SVProgressHUD setOffsetFromCenter:UIOffsetMake(self.centerX - screenW *0.5, 0)];
            [SVProgressHUD showInfoWithStatus:@"开始时间应小于结束时间！" maskType:SVProgressHUDMaskTypeGradient];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self endBtnClick:self.endBtn];
            });
            return;
        }else{//开始时间小于结束时间
            self.dateModel.endDate = date;
        }
    }
    self.model.beginDate = self.dateModel.beginDate;
    self.model.startTime = [self.fmt stringFromDate:self.dateModel.beginDate];
    self.model.endTime = [self.fmt stringFromDate:self.dateModel.endDate];
    self.model.endDate = self.dateModel.endDate;
    [self refreshTitle];
}
-(void)cancelBtnClick{
    self.beginBtn.enabled = YES;
    self.endBtn.enabled = YES;
}
#pragma mark - 隐藏键盘
- (void)hideTheKeyBoard
{
    [self endEditing:YES];
}

#pragma mark - 通知接收区

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
